<?php
namespace pay;
use  think\Request;
use   think\Config;

class Tlian{

    private  $apiKey;
    private  $callback;
    private  $notify_url;
    public function __construct()
    {
        $this->class =  $class = strtolower("Tlian");

            $this->Config  = $Config = Config::get($class);
            $this->apiKey = $Config['apiKey']; //秘钥
            $this->mchId = $Config['mchId'];//商户号
            $this->URL = $Config['URL'];//rrl

            $domain = Request::instance()->domain();
            //curl实例
            $this->http =new \http\Http();
        if(!empty($Config['callback_url'])){
            $this->callback = $Config['callback_url'];
        }else{
            $this->callback = $domain."/out/Notify/callbackurl";
        }
        if(!empty($Config['notify_url'])){
            $this->notify_url = $Config['notify_url'];
        }else{
            $this->notify_url =$domain."/out/Notify/handtl";
        }
        $this->daifunotify_url = $domain."/out/Notify/handtldaifu";
    }


    /**
     *  网关支付
     */
 /*   public function byPay($deposit,$payNo,$CertName,$CertNo,$Phone){



    }*/

    /**
     * @param $deposit
     * @param $payNo
     * @param $CertName
     * @param $CertNo
     * @param $Phone
     * @param $bank_code  PC 支付
     */
    public function pcPay($deposit,$payNo,$bank_code){
        $banklist = Config::get( $this->class."_bank");
        $pData = $this->payData2($deposit,$payNo,isset($banklist[$bank_code])?$banklist[$bank_code]:"01050000");
                    $pData['sign'] = $this->signature($pData);
        $form =  $this->createTable2($pData);
        return $form;

    }


    public function daiPay($deposit,$payNo,$card_name,$card_no,$bank_name=""){
        $pData =$this->payDatadaifu($deposit,$payNo,$card_name,$card_no,$bank_name);
        $pData['sign'] = $this->signature($pData);
        $form =  $this->createTabledaifu($pData);
        return $form;
    }



    /**
     * @param $deposit
     * @param $payNo
     * @param $CertName
     * @param $CertNo
     * @param $Phone
     * @param $bank_code  PC 支付
     */
    public function byPay($deposit,$payNo,$CertName,$CertNo,$Phone,$user_id=0){
        $pData = $this->payData($deposit,$payNo,$user_id);
        $pData['sign'] = $this->signature($pData);
       $form =  $this->createTable($pData);
        return $form;
    }

    public function createTable($data){
        $from = "    <form action='{$this->URL}{$this->actionList()['gate_gw_pay']}' id='myForm'  method='post'>";
        foreach($data as $k=>$v){
          $t = "  <input name='{$k}' type='text' value='{$v}'>";
            $from .=$t;
        }
        $from .="</form>";
        return $from;
        //
    }

    public function createTable2($data){
        $from = "    <form action='{$this->URL}{$this->actionList()['gategwpay']}' id='myForm'  method='post'>";
        foreach($data as $k=>$v){
            $t = "  <input name='{$k}' type='text' value='{$v}'>";
            $from .=$t;
        }
        $from .="</form>";
        return $from;
        //
    }
    public function createTabledaifu($data){
        $from = "    <form action='{$this->URL}{$this->actionList()['rtp_pay']}' id='form1'  method='post'>";
        foreach($data as $k=>$v){
            $t = " <input name='{$k}' type='text' value='{$v}'>";
            $from .=$t;
        }
        $from .="</form>";
        return $from;
        //
    }

    public function actionList(){
                $data = [];
                $data['gate_gw_pay'] = "/gate/epay/webApply";
                $data['gategwpay'] = "/gate/gw/pay";
                $data['rtp_pay'] = "/gate/rtp/pay";
                return $data;
    }




    public function payData2($deposit,$payNo,$bank_code){
        $data = [
            "mch_id"=>$this->mchId,
            "sp_id"=>$this->Config['sp_id'],
            "total_fee"=>bcmul($deposit,100),
            "out_trade_no"=>$payNo,//订单号
            "bank_code"=>$bank_code,//订单号
            "notify_url"=>$this->notify_url,//订单号
            "call_back_url"=>$this->callback,//订单号
            "user_type"=>1,
            "card_type"=>"DEBIT",
            "channel"=>1,
            "nonce_str"=>time(),
            "goods_name"=>"资金充值",
        ];

        return $data;
    }

    public function payDatadaifu($deposit,$payNo,$card_name,$card_no,$bank_name){
       /* sp_id
mch_id
out_trade_no
body
total_fee
card_name
card_no
bank_no
bank_name
acc_type
mobile
bank_branch_name
business_type
business_no
pay_type
notify_url
nonce_str*/
        $data = [
            "mch_id"=>$this->mchId,
            "sp_id"=>$this->Config['sp_id'],
            "total_fee"=>bcmul($deposit,100),
            "out_trade_no"=>$payNo,//订单号
            "body"=>"代付支出",//订单号
            "card_name"=>$card_name,
            "card_no"=>$card_no,
            "bank_name"=>$bank_name,

            "acc_type"=>"DEBIT",
            "business_type"=>"20101",
            "pay_type"=>"BALANCE",
            "notify_url"=>$this->daifunotify_url,
            "nonce_str"=>time(),
        ];

        return $data;
    }



    public function payData($deposit,$payNo,$user_id){

        /*$data = [
               "mch_id"=>$this->mchId,
               "sp_id"=>$this->Config['sp_id'],
               "total_fee"=>bcmul($deposit,100),
               "out_trade_no"=>$payNo,//订单号
               //"bank_code"=>$bank_code,//支付银行
               "goods_name"=>"资金充值",
                "notify_url"=>$this->notify_url,
                "call_back_url"=>$this->callback,
                "card_type"=>"DEBIT",
                "user_type"=>1,
                "channel"=>1,
                "nonce_str"=>time(),

           ];*/

        $data = [
            "mch_id"=>$this->mchId,
            "sp_id"=>$this->Config['sp_id'],
            "total_fee"=>bcmul($deposit,100),
            "out_trade_no"=>$payNo,//订单号
            "body"=>"资金充值",//订单号
            "notify_url"=>$this->notify_url,//订单号
            "front_url"=>$this->callback,//订单号
            "user_id"=>"dk_".$user_id,//订单号
            "nonce_str"=>time(),
        ];

        /*     服务商号	sp_id	是	String(32)	系统分配的服务商号
     商户号	mch_id	是	String(32)	由系统分配的商户号
     商户订单号	out_trade_no	是	String(32)	商户订单号，确保唯一
     总金额	total_fee	是	Int	订单总金额，单位为分
     商品名称	body	是	Stirng	商品名称
     通知地址	notify_url	是	String	快捷支付提交成功后回调的通知地址：务必确保外网可以访问
     前台跳转地址	front_url	否	String	快捷支付完成后页面跳转回到商户展示页面
     姓名	acc_name	否	String	姓名
     手机号	mobile	否	String
     证件类型	id_type	否	String(2)	01-身份证
     证件号码	id_no	否	String(32)
     卡号	acc_no	否	String	卡号
     卡类型	acct_type	否	String(10)	DEBIT-储蓄卡
     CREDIT-信用卡
     信用卡有效期	expire_date	否	String	当卡类型为：CREDIT 必填
     CVV	cvv	否	String	当卡类型为：CREDIT 必填
     用户号	user_id	是	String(32)	用户在合作方平台的唯一标识
     随机字符串	nonce_str	是	String(32)	随机字符串，不长于 32 位
     签名	sign	是	String(32)	MD5 签名结果，详见“签名说明”*/




        return $data;
    }


    public function Notify($result){
        $files = "/home/wwwlogs/controller_Notify_tilian.log";
        $tdata = ["msg"=>"异常","status"=>0,"data"=>[]];
        $arr = ["sp_id","mch_id","out_trade_no","trade_no","trade_state","total_fee","nonce_str"];
        //$arr = ksort($arr);signature
        if(getOS()=="Linux"){
            error_log($result.PHP_EOL,3,$files);
        }

        $result = parse_str($result, $arrs);

        if(empty($arrs)){
            return array_merge($tdata,['status'=>0,"msg"=>"通知"]);
        }
        $result = $arrs;


        if($result['trade_state']!="SUCCESS"){ //充值成功

            // 回滚事务
            if(getOS()=="Linux"){
                error_log("订单号".$result['trade_no']."已被银行折返".PHP_EOL,3,$files);
            }
            return array_merge($tdata,['status'=>0,"msg"=>"改订单已被银行折返"]);
        }

        $darr = [];
        foreach ($result as $k=>$v){
                if(!empty($v)&&in_array($k,$arr)){
                    $darr[$k] = $v;
                }
        }
        ksort($darr);//字典排序

        $signature = $this->signature($darr);

        if(strtoupper($signature) !=strtoupper($result['sign']) ){//
            if(getOS()=="Linux"){
                error_log("订单号".$result['trade_no']."签名失败",3,$files);
            }
            return array_merge($tdata,["msg"=>"签名失败"]);
        }



        $NotifySignModel  = new \app\admin\model\UsersRecharge();
        $res = $NotifySignModel->where("thirdparty_payno",$result['out_trade_no'])->find();
        if($res['status']==2){
            if(getOS()=="Linux"){
                error_log("订单号".$result['out_trade_no']."已失效",3,$files);
            }
            return array_merge($tdata,['status'=>0,"msg"=>"该订单已失效"]);
        }
        if($res['status']==1){

            if(getOS()=="Linux"){
                error_log("订单号".$result['out_trade_no']."已充值成功",3,$files);
            }
            echo("SUCCESS");exit;
            return array_merge($tdata,['status'=>0,"msg"=>"该订单已充值成功"]);
        }

        $resultBa['app_id'] =$result['out_trade_no'];
        $resultBa['amount'] =$result['total_fee'];


        return  ["data"=>$resultBa,"status"=>1,"msg"=>"验证成功"];


    }








    /**
     *   生成签名
     */
    public function signature($data){
        ksort($data);//字典排序
        $dataString = "";
        foreach($data as $k=>$v){
            $dataString .=$k."=".$v."&";
        }
        $stringSignTemp =  $dataString."key=".$this->apiKey;
        $md5String = strtoupper(md5($stringSignTemp));
        return $md5String;
    }




    /**
     * @return array 获取那个基本参数
     */
    private function baseData(){
       $data = [
           "mchId"=>$this->mchId,
           "timestamp"=>date("YmdHis")."000",
           "data"=>"",
       ];
        return $data;
    }





}
?>
